<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */


namespace app\shop_admin\service;

use app\index\service\InventoryService;
use app\index\service\SendMsgService;
use app\shop_admin\model\AfterOrderCommodity;
use app\shop_admin\model\AfterProcess;
use app\shop_admin\model\AgentBillTemporary;
use app\shop_admin\model\Coupon;
use app\shop_admin\model\GroupCommodity;
use app\shop_admin\model\Order;
use app\shop_admin\model\OrderAfter;
use app\shop_admin\model\OrderCommodity;
use app\shop_admin\model\OrderFreight;
use app\shop_admin\model\RechargeRecord;
use app\shop_admin\model\ReturnAddress;
use app\shop_admin\model\User;
use app\shop_admin\model\UserCash;
use app\shop_admin\model\UserCoupon;
use app\utils\Addons;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\exception\HttpException;
use think\facade\Cache;
use think\facade\Db;
use app\utils\SendMsg;
use think\facade\Request;
use think\db\Query;

class AfterSaleService
{
    private $mid;

    public function __construct()
    {
        global $user;
        $this->mid = $user['mall_id'];
    }

    /**
     * @param array $data
     * @param int $page
     * @param int $size
     * @return array
     */
    public $data;
    private $order_commodity_id = [];

    public function afterSaleList(array $data, int $page = 1, int $size = 10)
    {
        $res = Order::alias('a')
            ->where($this->bulidWhere($data))
            ->join('user u', 'a.user_id=u.id', 'LEFT')
            ->join('order_commodity o', 'a.id=o.order_id', 'LEFT')
            ->join('order_freight r', 'a.id=r.order_id', 'LEFT')
            ->join('commodity c', 'o.commodity_id=c.id', 'LEFT')
            ->join('order_after f', 'a.id=f.order_id', 'LEFT')
            ->field('
           a.order_no,a.pay_no,a.create_time,a.id,a.status,a.money,a.address,a.pay_id,any_value(r.freight) as freight,f.state,
           u.nickname,u.picurl,IFNULL(a.consignee,"暂无") as user_real_name,IFNULL(a.iphone,"暂无") as user_mobile,a.after_type,
           a.has_attach,a.discount_level_money
           ')
            ->with(['orderCommoditys', 'orderCommoditys.orderAfter'])
            ->group('a.id')
            ->order('a.id desc')
            ->paginate(['page' => $page, 'list_rows' => $size]);
        foreach ($res as $k => $v) {
            if ($v['has_attach'] == 1) {
                $res[$k]['attach'] = Db::name("order_commodity_attach")->where('order_id', $v['id'])->select();
            }
        }
        return [HTTP_SUCCESS, $res];
    }

    /**获取维权订单详情
     * @param int id 退货订单id
     * @return array
     * @throws DataNotFoundException
     * @throws ModelNotFoundException*@throws DbException
     * @throws DbException
     */
    public function afterInfo($id)
    {
        $res = OrderAfter::with(['process', 'order' => function ($query) {
            $query->field('order_no,pay_id,pay_no,type,pay_time,status,id,has_attach');
        }, 'afterCommodity' => function ($query) {
            $query->alias('a')
                ->join('order_commodity o', 'a.ocid=o.id', 'LEFT')
                ->join('commodity c', 'o.commodity_id = c.id', 'LEFT')
                ->join('sku s', 'o.sku_id=s.id', 'LEFT')
                ->join('sku_inventory k', 'o.sku_id=k.sku_id', 'LEFT')
                ->join('order_after r', 'a.order_after_id = r.id', 'LEFT')
                ->field('c.name,c.master,s.pvs_value,r.imgs,
                (case when c.has_sku = 1 then k.sell_price else c.sell_price end) as sell_price,o.after_type,
                o.count,o.after_status,o.id,a.ocid,a.order_after_id,o.sku_id');
        }, 'order.user'])
            ->where('mall_id', $this->mid)
            ->find($id);
        !empty($res) && $res->hidden(['update_time', 'delete_time']);
        if ($res['order']['has_attach'] == 1) {
            $res['order']['attach'] = Db::name("order_commodity_attach")->where('order_id', $res['order']['id'])->select();
        }
        return [HTTP_SUCCESS, $res];
    }

    /**修改维权订单状态
     * @param array $arr
     * @return array|void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws \think\Exception
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function upAfterState(array $arr)
    {

        $this->data = OrderAfter::with(['afterCommodity' => function ($query) {
            $query->alias('a')
                ->join('order_commodity o', 'a.ocid=o.id', 'LEFT')
                ->join('commodity c', 'o.commodity_id = c.id', 'LEFT')
                ->join('sku_inventory s', 'o.sku_id = s.sku_id', 'LEFT')
                ->field('o.commodity_id,(CASE WHEN c.has_sku THEN s.sell_price ELSE c.sell_price END) AS sell_price,o.is_out_sell,
                o.count,o.sku_id,a.order_after_id,a.ocid,c.inventory_type,o.mall_id');
        }])
            ->find($arr['id'])
            ->toArray();
        if(!empty($this->data['mall_id'])){
            global $m_id;
            $m_id=$this->data['mall_id'];
        }


        switch ($arr['state']) {
            case 2:
                return $this->agree($arr);//同意申请
                break;
            case 3:
                return $this->reject($arr);//驳回申请
                break;
            case 4:
                return $this->confirm($arr);//换货-确认发货
                break;
            case 5:
                return $this->manualRefund($arr);//手动退款
                break;
            case 6:
                return $this->autoRefund($arr);//自动退款
                break;
            case 7:
                return $this->agreeRefund($arr);//同意退款
                break;
            case 8:
                return $this->close();//关闭申请
                break;
        }
    }

    /** 同意申请
     * @param array $arr
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private function agree(array $arr)
    {
        //2-退货退款
        //3-换货
        //$order = Order::find($this->data['order_id']);
        // 1-等待商家处理 2-同意申请 3-驳回申请 4-商家已发货，等待客户收货 5-手动退款  6-确认发货 7-退款退货完成 8-退款完成 9-换货完成 10-退回物品,等待退款  11-同意退款 12-等待买家退回商品 13-买家退回物品，等待退款 14-买家退回物品，等待商家重新发货
        $res = OrderAfter::update(['after_address_id' => $arr['after_address_id'], 'state' => 12], ['id' => $this->data['id']]);
        $this->upStep($arr['id'], ['step' => 2, 'handle_time' => date('Y-m-d H:i:s', time()), 'state' => 1, "step_name" => "处理维权成功"]);
        $order_commodity_id = AfterOrderCommodity::field('ocid')->where('order_after_id', $this->data['id'])
            ->where('mall_id', $this->mid)->select()->toArray();
        AgentBillTemporary::orderCommodityDel(array_column($order_commodity_id, 'ocid'));
        return [HTTP_SUCCESS, $res];
    }

    /**
     * 仅退款-自动退款
     * @param array $arr
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws \think\Exception
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function autoRefund(array $arr)
    {
        $res = $this->refund($this->data['order_id'],
            $this->data['money'],
            $this->data['afterCommodity'], true);
        if ((new Addons())->check($this->mid, 3))
            $this->return_coupon($this->data['order_id']);
        $this->upStep($arr['id'], [
            ['step' => 2, 'handle_time' => date('Y-m-d H:i:s', time()), 'state' => 1],
            ['step' => 3, 'handle_time' => date('Y-m-d H:i:s', time()), 'state' => 1, 'step_name' => '退款成功'],
        ]);
        //4-商家已发货，等待客户收货 5-  6-确认发货 7-退款退货完成 8-退款完成 9-换货完成 10-退回物品,等待退款  11-同意退款 12-等待买家退回商品 13-买家退回物品，等待退款 14-买家退回物品，等待商家重新发货
        OrderAfter::update(['state' => 8], ['id' => $arr['id']]);
        //订单 订单-商品
        $this->upOrderCommodityState($arr['id'], 2);
        $this->AfterStatus($this->data['order_id']);
        AgentBillTemporary::orderCommodityDel($this->order_commodity_id);
        $this->sendMsg();
        return [HTTP_SUCCESS, $res];
    }

    private function sendMsg()
    {
        $order = Order::with(['orderCommodity' => function (Query $query) {
                $query->alias('a')
                    ->join('commodity c', 'a.commodity_id = c.id', 'LEFT')
                    ->field('c.name,a.express_company,a.logistics_no,a.order_id');
            }])
            ->find($this->data['order_id'])
            ->toArray();
        $arr['str'] = "";
        foreach ($order['orderCommodity'] as $v) {
            $arr['str'] .= $v['name'] . "-";
        }
        $user = User::find($order['user_id']);
        $send = new SendMsg("订单手动退款通知");
        $url = Request::domain() . "/h5/#/orderpage/order/orderdetail?type=4&id=" . $order['id']."&mall_id=". $order["mall_id"];
        $data = [
            "commodity_refund_name" => $arr['str'],
            "order_no" => $order['order_no'],
            "order_create_time" => $order['create_time'],
            "refund_cash" => $order['money']
        ];
        $send->send($user, $data, $url);
    }

    /**驳回申请
     * @param array $arr
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function reject(array $arr)
    {
        $find = OrderAfter::with('afterCommodity')->find($arr['id']);
        OrderAfter::update(['reject_remake' => $arr['reject_remake'], 'state' => 3], ['id' => $arr['id']]);
        $type = $find['type'] == 2 ? 1 : 0;
        $this->upStep($arr['id'], [
            ['step' => 2, 'handle_time' => date('Y-m-d H:i:s', time()), 'state' => 1, 'step_name' => "驳回申请"],
            ['step' => 3, 'handle_time' => date('Y-m-d H:i:s', time()), 'state' => 3, 'step_name' => $find['type_text'] . "失败"],
        ], $type);
        AfterProcess::where('order_after_id', $arr['id'])->where('mall_id', $this->mid)->where('step', '>', '3')->delete();

        //$data = $find->toArray();
        //foreach ($data['afterCommodity'] as $v) {
        //   OrderCommodity::update(['status' => 11], ['id' => $v['ocid']]);
        // }
        $this->upOrderCommodityState($find['id'], 4);
        $this->AfterStatus($this->data['order_id']);
        $this->upOrderState($find['order_id']);
        return [HTTP_SUCCESS, "成功!"];
    }

    /**同意退款
     * @param array $arr
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function agreeRefund(array $arr)
    {
        $type = OrderAfter::where('id', $this->data['id'])->value('type');

        //1-仅退款 2-退货退款 3-换货
        //7-退款退货完成 8-退款完成 9-换货完成
        $state = [2 => 7, 3 => 9];
        if ((new Addons())->check($this->mid, 3))
            $this->return_coupon($this->data['order_id']);
        $step_name = [2 => "退款退货完成", 3 => "换货完成"];
        OrderAfter::update(['state' => $state[$type]], ['id' => $this->data['id']]);
        foreach ($this->data['afterCommodity'] as $v) {
            $order_comodity_id[] = $v['ocid'];
            OrderCommodity::update(['after_status' => 2], ['id' => $v['ocid']]);
        }
        AgentBillTemporary::orderCommodityDel($order_comodity_id);
        $status = OrderCommodity::where('order_id', $this->data['order_id'])->field('after_status')->group('after_status')->select()->toArray();
        $arr = array_column($status, 'after_status');
        $flag = 2;
        foreach ($arr as $v) {
            if (in_array($v, [1])) $flag = 1;
        }
        if ($flag) Order::update(['after_status' => $flag], ['id' => $this->data['order_id']]);

        $data = [
            ['step' => 2, 'handle_time' => date('Y-m-d H:i:s', time()), 'state' => 1, 'step_name' => '处理维权'],
            ['step' => 3, 'handle_time' => date('Y-m-d H:i:s', time()), 'state' => 1, 'step_name' => "客户退回物品成功"],
            ['step' => 4, 'handle_time' => date('Y-m-d H:i:s', time()), 'state' => 1, 'step_name' => $step_name[$type]]
        ];
        $this->upStep($this->data['id'], $data, $type);
        $this->AfterStatus($this->data['order_id']);
        $this->refund($this->data['order_id'], $this->data['money'], $this->data['afterCommodity'], true);
        return [HTTP_SUCCESS, '成功!'];
    }

    /**手动退款
     * @param array $arr
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws \think\Exception
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function manualRefund(array $arr)
    {

        count($this->data['afterCommodity']) == count($this->data['afterCommodity'], 1) ? $arr[] = $this->data['afterCommodity'] : $arr = $this->data['afterCommodity'];
        if ((new Addons())->check($this->mid, 3))
            $this->return_coupon($this->data['order_id']);
        if ($this->data['type'] == 2) {
            $this->upStep($this->data['id'], [
                ['step' => 2, 'handle_time' => date('Y-m-d H:i:s', time()), 'state' => 1, 'step_name' => '处理维权成功'],
                ['step' => 3, 'handle_time' => date('Y-m-d H:i:s', time()), 'state' => 1, 'step_name' => '客户退回物品'],
                ['step' => 4, 'handle_time' => date('Y-m-d H:i:s', time()), 'state' => 1, 'step_name' => $this->data['type_text'] . "成功"]]);
        } elseif ($this->data['type'] == 3) {
            AfterProcess::where('order_after_id', $this->data['id'])->where('step', 'in', [3, 4])->delete();
            AfterProcess::create(["order_after_id" => $this->data['id'], 'step' => 3, 'handle_time' => date('Y-m-d H:i:s', time()), 'state' => 1, 'step_name' => $this->data['type_text'] . "成功"]);
        } elseif ($this->data['type'] == 1) {
            $this->upStep($this->data['id'], [['step' => 2, 'handle_time' => date('Y-m-d H:i:s', time()), 'state' => 1, 'step_name' => '处理维权成功'],
                ['step' => 3, 'handle_time' => date('Y-m-d H:i:s', time()), 'state' => 1, 'step_name' => $this->data['type_text'] . "成功"]]);
        }
        $state = ["退款" => 8, "退货退款" => 7, "换货" => 9];

        OrderAfter::update(['state' => $state[$this->data['type_text']]], ['id' => $this->data['id']]);
        $this->upOrderCommodityState($this->data['id'], 2);
        $this->AfterStatus($this->data['order_id']);
//        $this->refund($this->data['order_id'],
//            $this->data['money'],
//            $this->data['afterCommodity'], true);
        AgentBillTemporary::orderCommodityDel($this->order_commodity_id);
        $order = Order::find($this->data['order_id']);
        // 拼团库存
        if ($order['order_from'] == 1) {
            $order_commodity = OrderCommodity::where('order_id', $order['id'])->find();
            $gc_id = explode(',', $order_commodity['gc_id'])[0];
            $num = $order_commodity['count'];

            if (is_null($order_commodity['sku_id'])) {
                Db::name('group_commodity')
                    ->where('id', $gc_id)
                    ->inc("activity_stock", $num)->update();
            } else {
                Db::name('group_commodity_sku')
                    ->where('gc_id', $gc_id)
                    ->where('sku_id', $order_commodity['sku_id'])
                    ->inc("activity_stock", $num)->update();
            }
        }
        $this->judgeDrawback($this->data['order_id']);
        return [HTTP_SUCCESS, "成功了"];
    }

    /** 退款 回滚库存
     * @param int $oid
     * @param float $money
     * @param array $arr
     * @param bool $flag
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws \think\Exception
     */
    private function refund(int $oid, float $money, array $arr, bool $flag = false)
    {
        try {
            $find = Order::with(['orderAfter', 'orderCommodity'])->find($oid);
            // 拼团库存
            if ($find['order_from'] == 1) {
                $order_commodity = $find->orderCommodity[0];
                $gc_id = explode(',', $order_commodity['gc_id'])[0];
                $num = $order_commodity['count'];

                if (is_null($order_commodity['sku_id'])) {
                    Db::name('group_commodity')
                        ->where('id', $gc_id)
                        ->inc("activity_stock", $num)->update();
                } else {
                    Db::name('group_commodity_sku')
                        ->where('gc_id', $gc_id)
                        ->where('sku_id', $order_commodity['sku_id'])
                        ->inc("activity_stock", $num)->update();
                }
            }
            if (in_array($find->getData('status'), [2]) && in_array($find['after_type'], [1])) {//未发货状态下 整单维权
                $freight = OrderFreight::where('order_id', $oid)->value('freight');
                $money += $freight;
            }
            if (in_array($find['after_type'], [1]) && in_array($this->data['type'], ['1', '2'])) {
                if (!$find['is_rebate'])
                    Order::update(['settlement' => 3], ['id' => $oid]);
            }
            $this->judgeDrawback($oid);

            if ($find->getData('pay_id') == 1) {
                $cash = UserCash::where('user_id', $find['user_id'])->find();
                UserCash::where('user_id', $find['user_id'])->inc('total', $money)->update();
                UserCash::where('user_id', $find['user_id'])->dec('expense', $money)->update();
                $data = [
                    "user_id" => $find['user_id'],
                    "base_in" => "admin",
                    "source_type" => 6,
                    "source" => "退款",
                    "type" => 0,
                    'old_cash' => $cash['total'],
                    'new_cash' => bcadd($cash['total'], $money, 2),
                    "money" => $money,
                    "remark" => "维权订单退款",
                    "trade" => $find['order_no']
                ];
                RechargeRecord::create($data);
                $arr1 = true;
            } elseif (in_array($find->getData('pay_id'), [1, 2, 3])) {
                $pay = new PaymentService();
                //dd($pay->refund($oid, ['refund' => $money]));
                $arr1 = $pay->refund($oid, ['refund' => $money]);

            }

            if ($flag) {
                foreach ($arr as $v) {
                    // 订单状态: 1-待支付 2-待发货 3-已发货 4-已完结 5-已评价   6-删除 7-已收货 8-维权中 9-已维权 10-维权驳回 11-已关闭
                    if (!$v['is_out_sell'] || (in_array($v['inventory_type'], [3]) && in_array($v['status'], [2, 3, 7])) || (in_array($v['inventory_type'], [1, 2]))) {//付款减库存
                        $inventory = new InventoryService($v['commodity_id']);
                        $inventory->backInventory($v['count'], $v['sell_price'], $v['sku_id']);
                    }

                }
            }
            return [HTTP_SUCCESS, '退款成功!'];
        } catch (DataNotFoundException $e) {
            throw new DataNotFoundException($e->getMessage());
        } catch (ModelNotFoundException $e) {
            throw new ModelNotFoundException($e->getMessage());
        } catch (DbException $e) {
            throw new DbException($e->getMessage());
        }
    }

    /** 换货 -确认发货 无需寄回商品直接发货
     * @param array $arr
     * @return array
     */
    public function confirm(array $arr)
    {
        $res = OrderAfter::update([
            'deliver_num' => $arr['deliver_num'],
            'deliver_company' => $arr['deliver_company'],
            'deliver_time' => $arr['deliver_time'],
            'state' => 4
        ], ['id' => $arr['id']]);

        $this->upStep($arr['id'], [
            ['step' => 2, 'handle_time' => date('Y-m-d H:i:s', time()), 'state' => 1, 'step_name' => "处理维权"],
            ['step' => 3, 'handle_time' => date('Y-m-d H:i:s', time()), 'state' => 1, 'step_name' => "商家重新发货"],
            ['step' => 4, 'handle_time' => null, 'state' => 2, 'step_name' => "换货成功"]
        ]);
        AfterProcess::where('order_after_id', $arr['id'])->where('step', 5)->delete();

        return [HTTP_SUCCESS, $res];
    }

    /** 换货-关闭申请
     * @return array
     */
    public function close()
    {
        $res = OrderAfter::update(['state' => 9], ['id' => $this->data['id']]);
        foreach ($this->data['afterCommodity'] as $v) {
            OrderCommodity::update(['after_status' => 2, 'status' => 11], ['id' => $v['ocid']]);
        }
        $states = OrderCommodity::where('order_id', $this->data['order_id'])
            ->field('after_status')
            ->group('after_status')
            ->select()
            ->toArray();
        $state = 2;
        foreach ($states as $v) {
            if (in_array($v, [1])) $state = 1;
        }
        $data['after_status'] = $state;
        if ($this->data['type'] == 3) $data['status'] = 12;
        Order::where('id', $this->data['order_id'])->where('mall_id', $this->mid)->update($data);
        $this->upStep($this->data['id'], ['step' => 4, 'handle_time' => date('Y-m-d H:i:s', time()), 'state' => 1, 'step_name' => "换货成功"]);
        return [HTTP_SUCCESS, $res];
    }

    /**修改退货流程
     * @param int $id 退货订单ID
     * @param array $data
     * @param int $type
     * @return bool
     */
    public function upStep(int $id, array $data = [], int $type = 0)
    {
        count($data) == count($data, 1) ? $list[] = $data : $list = $data;
        $up = 0;
        if ($type) AfterProcess::where('order_after_id', $id)->where('step', 5)->delete();
        if ($type == 1) AfterProcess::where('order_after_id', $id)->where('step', 4)->delete();

        foreach ($list as $v) {
            $step = $v['step'];
            unset($v['step']);
            $up = AfterProcess::where('order_after_id', $id)->where('step', $step)->update($v);
        }
        if (false !== $up)
            return true;
        else
            return false;
    }

    /**更新订单状态
     * @param int $oaid
     * @param int $state
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function upOrderCommodityState(int $oaid, int $state)
    {
        $res = OrderAfter::with(['afterCommodity' => function ($query) {
            $query->field('order_after_id,ocid');
        }])
            ->find($oaid)
            ->toArray();
        $ids = array_column($res['afterCommodity'], 'ocid');
        $data['after_status'] = $state;
        //if ($state == 4) $data['status'] = 11;
        foreach ($ids as $v) {
            $this->order_commodity_id[] = $v;
            OrderCommodity::update($data, ['id' => $v]);
        }
        $arr = OrderCommodity::where('order_id', $res['order_id'])->field('after_status')->group('after_status')->select()->toArray();
        $flag = $state;
        //维权状态: 1- 维权中 2-已维权 3-未维权
        foreach ($arr as $v) {
            if (in_array($v['after_status'], [1])) $flag = 1;
        }
        Order::update(['after_status' => $flag], ['id' => $res['order_id']]);

    }

    /**获取退货地址
     * @param int $page
     * @param int $size
     * @return array
     * @throws DbException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function getAfterAddress(int $page = 1, int $size = 10)
    {
        global $token;
        $token = "shop_" . createToken();
        if (Cache::store('redis')->has('TOKEN:SHOP:' . $token)) {
            $admin = Cache::store('redis')->get('TOKEN:SHOP:' . $token);
            $js = json_decode($admin, true);
            $merchantId = $js['merchant_id'];
        } else {
            $merchantId = 1;
        }

        $res = ReturnAddress::where('merchant_id', $merchantId)
            ->where('status', 1)
            ->order('id desc')
            ->field('name,id')
            ->paginate(['page' => $page, 'list_rows' => $size]);

        return [HTTP_SUCCESS, $res];
    }

    private function bulidWhere(array $data)
    {
        global $user;
        $where = [];
        $arr = [];
        $res = [];
        $where[] = ['a.type', '=', 2];
        $where[] = ['a.mall_id', '=', $this->mid];
        $where[] = ['a.merchant_id', '=', $user->merchant_id];
        !empty($data['order_no']) && $where[] = ['a.order_no', '=', $data['order_no']];
        !empty($data['order_type']) && $where[] = ['a.order_type', '=', $data['order_type']];
        !empty($data['pay_type']) && $where[] = ['a.pay_id', '=', $data['pay_type']];
        !empty($data['status']) && $where[] = ['a.status', '=', $data['status']];
        !empty($data['after_status']) && $where[] = ['a.after_status', '=', $data['after_status']];
        !empty($data['after_type']) && $where[] = ['o.after_type', '=', $data['after_type']];
        if (array_key_exists('type', $data) && !empty($data['type']) && (array_key_exists('keyword', $data) && !empty(trim($data['keyword']))))
            $res = $this->setType($data['type'], $data['keyword']);
        if (array_key_exists('start_time', $data) && array_key_exists('end_time', $data))
            $arr = $this->setTime($data['start_time'], $data['end_time']);
        return array_merge($where, $arr, $res);
    }

    private function setType($type, $value)
    {
        $where = [];
        switch ($type) {
            // 1 会员ID 2 会员信息 3 收件人信息 4地址信息 5 商品名称 6 商品编号 7 订单编号
            case 1:
                $where[] = ['a.user_id', '=', $value];
                break;
            case 2:
                $where[] = ['u.nickname|u.name', '=', $value];
                break;
            case 3:
                $where[] = ['a.consignee', '=', trim($value)];
                break;
            case 4:
                $where[] = ['a.address', 'like', '%' . trim($value) . '%'];
                break;
            case 5:
                $where[] = ['c.name', 'like', trim($value) . '%'];
                break;
            case 6:
                $where[] = ['c.id', '=', trim($value)];
                break;
            case 7:
                $where[] = ['a.order_no', '=', trim($value)];
                break;
        }

        return $where;
    }

    private function setTime($start_time, $end_time)
    {
        $arr = [];
        if (!empty($start_time) && !empty($end_time))
            $arr[] = ['a.create_time', 'between', [$start_time, $end_time]];
        elseif (!empty($start_time) && empty($end_time))
            $arr[] = ['a.create_time', 'between', [$start_time, date('Y-m-d H:i:s', time())]];
        elseif (empty($start_time) && !empty($end_time))
            $arr[] = ['a.create_time', 'between', [date('Y-m-d H:i:s', strtotime($end_time) - 60), $end_time]];
        return $arr;
    }

    /**
     * @param string $oid
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private function AfterStatus(string $oid)
    {
        //1-等待商家处理 2-同意申请 3-驳回申请 4-商家已发货，等待客户收货 5-手动退款  6-确认发货 7-退款退货完成 8-退款完成 9-换货完成
        // 10-退回物品,等待退款  11-同意退款 12-等待买家退回商品 13-买家退回物品，等待退款 14-买家退回物品，等待商家重新发货
        $res = OrderAfter::where('order_id', $oid)->where('mall_id', $this->mid)->with(['afterCommodity'])->field('state,id')->select()->toArray();
        foreach ($res as $v) {
            if (in_array($v['state'], [7, 8, 9])) {
                foreach ($v['afterCommodity'] as $vv) {
                    OrderCommodity::where('id', $vv['ocid'])->where('mall_id', $this->mid)->update(['status' => 11]);
                }
            }
        }
        $this->upOrderState($oid);
    }

    /**
     * @param string $oId
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private function upOrderState(string $oId)
    {
        upOrderState($oId);
        $order = Order::find($oId);
        $state = $order->getData('status');

        if ($state == 12) {
            $settlement = Db::table('jiecheng_merchant_settlement')->where(['id' => $oId])->find();
            Db::table('jiecheng_merchant_cash')
                ->where(['mall_id' => $settlement['mall_id'], 'merchant_id' => $settlement['merchant_id']])
                ->inc('total', (float)bcadd((string)$settlement['account'], (string)$settlement['agent_cash']))
                ->inc('recharge', (float)bcadd((string)$settlement['account'], (string)$settlement['agent_cash']))
                ->update();
            Db::table('jiecheng_order')->where(['id' => $settlement['id']])->update(['settlement' => 2]);
        }
    }

    /** 退还优惠券
     * @param int $oId
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private function return_coupon(int $oId)
    {
        $find = Order::find($oId);
        $user_coupon = UserCoupon::where('unified_order_no', $find['order_no'])->where('mall_id', $this->mid)->find();
        if (empty($user_coupon)) return;
        $coupon = Coupon::where('id', $user_coupon['coupon_id'])->where('mall_id', $this->mid)->find();
        $flag = true;
        $ids = OrderCommodity::where('order_id', $oId)->where('mall_id', $this->mid)->field('id')->select()->toArray();
        $id_arr = array_column($ids, 'id');
        $after_ids = OrderAfter::where('order_id', $oId)->where('mall_id', $this->mid)->field('id')->select()->toArray();
        $afters = array_column($after_ids, 'id');
        $ocids = AfterOrderCommodity::where('order_after_id', 'in', $afters)->where('mall_id', $this->mid)->field('ocid')->select()->toArray();
        $ocids_arr = array_column($ocids, 'ocid');
        $tally = count(array_diff($id_arr, $ocids_arr));

        //1-待支付 2-待发货 3-已发货 4-已完结 5-已评价   6-删除 7-部分发货 8-已收货 9-部分收货 10-维权中 11-维权完成 12-已关闭
        if (!in_array($find->getData('status'), [1, 2, 3, 7, 9]) || $tally > 1) {
            return;
        }
        if (!empty($coupon['limit_indate_begin']) && !empty($coupon['limit_indate_end'])) {
            if (time() < strtotime($coupon['limit_indate_begin']) || time() > strtotime($coupon['limit_indate_end'])) {
                $flag = false;
            }
        }
        if ($coupon['user_limit_type'] = 1) {
            $count = UserCoupon::where('user_id', $find['user_id'])
                ->where('coupon_id', $user_coupon['coupon_id'])
                ->where('mall_id', $this->mid)
                ->count();
            if ($count >= $coupon['user_limit']) {
                $flag = false;
            }
        }
        if ($flag) {
            $user_coupon->unified_order_no = null;
            $user_coupon->status = 0;
            $user_coupon->save();
        }
    }


    private function judgeDrawback(int $oid)
    {
        $find = Order::with(['orderAfter', 'orderCommodity'])->find($oid);
        $ids = [];
        if (!empty($find)) {
            $find1 = $find->toArray();
            $ids = array_column($find1['orderCommodity'], 'id');
        }
        $afters = OrderAfter::where('order_id', $oid)
            ->alias('a')
            ->join('after_order_commodity o', 'a.id=o.order_after_id', 'LEFT')
            ->field('o.ocid')
            ->select();
        if (!empty($afters)) $afters = $afters->toArray();
        $afters_ids = array_column($afters, 'ocid');
        if (empty(array_diff($ids, $afters_ids))) {
            if (!$find['is_rebate'])
                Order::update(['settlement' => 3], ['id' => $oid]);
        }

    }

}